package myToolTest;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JFileChooser;

import mytool.Time;

public class EnDEcript {
	public static void main(String[] args) throws IOException {
		Time.start();
//		encript();
		 decript();
		Time.end();
	}

	private static void decript() throws IOException {
		JFileChooser chooser = new JFileChooser();
		int option = chooser.showOpenDialog(null);
		if (option == JFileChooser.APPROVE_OPTION) {
			File f = chooser.getSelectedFile();
			decript(f);
		}
	}

	private static void decript(File src) throws IOException {
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(
				src));
		String dest = src.getAbsolutePath().substring(0,
				src.getAbsolutePath().length() - 4)
				+ "-decripted"
				+ src.getAbsolutePath().substring(
						src.getAbsolutePath().length() - 4);
		BufferedOutputStream out = new BufferedOutputStream(
				new FileOutputStream(dest));
		long count = 0;
		int b;
		in.skip(7);
		while ((b = in.read()) != -1) {
			if (count % 4 == 1) {
				b = ((b << 1) | (b >> 7));
			} else if (count % 4 == 3) {
				b = (b >> 2) | (b << 6);
			} else {

			}
			out.write(b);
			count++;
		}
		in.close();
		out.close();

	}

	private static void encript() throws IOException {
		JFileChooser chooser = new JFileChooser();
		int option = chooser.showOpenDialog(null);
		if (option == JFileChooser.APPROVE_OPTION) {
			File f = chooser.getSelectedFile();
			encript(f);
		}
	}

	private static void encript(File src) throws IOException {
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(
				src));
		String dest = src.getAbsolutePath().substring(0,
				src.getAbsolutePath().length() - 4)
				+ "-encripted"
				+ src.getAbsolutePath().substring(
						src.getAbsolutePath().length() - 4);
		BufferedOutputStream out = new BufferedOutputStream(
				new FileOutputStream(dest));
		String author = "heantai";
		out.write(author.getBytes("gbk"));
		out.flush();
		int b;
		long count = 0;
		while ((b = in.read()) != -1) {
			if (count % 4 == 1) {
				b = ((b >> 1)) | (b << 7);
			} else if (count % 4 == 3) {
				b = (b << 2) | (b >> 6);
			} else {

			}
			out.write(b);
			count++;
		}
		out.close();
		in.close();
	}
}
